<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2018/12/11
 * Time: 15:46
 */

namespace app\modules\responsibilitiesChain;


abstract class Handler
{
    /**
     * @var Handler|null 你的上级对象
     */
    public $successor = null;

    /**
     * Handler constructor.
     * @param Handler|null $handler
     */
    public function __construct(Handler $handler = null)
    {
        $this->successor = $handler;
    }

    /**
     * 通过使用模板方法模式这种方法可以确保每个子类不会忽略调用继承
     *
     * @date   2018/12/11
     * @author edmmss
     * @param Request $request
     * @return mixed
     */
    final public function handle(Request $request)
    {
        $apply = $this->apply($request);

        if ($apply === null && $this->successor !== null) {
            // 请求尚未被目前的处理器处理并且设置了上级，将传递到你的上级处理
            $apply = $this->successor->handle($request);
        }

        return $apply;
    }

    /**
     * 声明处理方法
     *
     * @date   2018/12/11
     * @author edmmss
     * @param Request $request
     * @return mixed
     */
    abstract public function apply(Request $request);
}